<?php
    /* Fingon 2011.07 */
    require_once('global.php');
    require_once('/code/Include/db_mysql.php');
    require_once('/code/Include/thumb_handler.php');
    require_once('/code/SiteInfo.php');

    Class Product
    {
        protected $db;
        
        const IMG_MAX_W=600;
        const IMG_MAX_H=600;
        //const IMG_WATERMARK_FONTSIZE=20;
        const IMG_WATERMARK_OFFSET_X=15;
        const IMG_WATERMARK_OFFSET_Y=-10;
        const THUMB_MAX_W=190;
        const THUMB_MAX_H=170;
        //const THUMB_WATERMARK_FONTSIZE=5;
        const THUMB_WATERMARK_OFFSET_X=5;
        const THUMB_WATERMARK_OFFSET_Y=-5;
        const IMG_LOCATION='/gallery/images/';
        const IMG_THUMB_SUFFIX='thumb';
        //const WATERMARK_TEXT='© PhotoFromThe1st.com';
        const WATERMARK_FONT='./code/Include/ariblk.ttf';
        //const WATERMARK_PCT=20;

        public function Product()    {
            $this->db=new DB();
        }
        
        public function getProductsByCategory($cid, $active_only=1, $page=0, $count=0, $sort='order by create_time DESC')   {
            $sql='select product.*, artist.name from `product` left join `artist` on product.artist_id=artist.artist_id where category_id = '.$cid.($active_only ? ' && product.is_active = 1' : '').' '.$sort.($page*$count ? ' limit '.($page-1)*$count.','.$count : '');
            return $this->db->get_rows($sql);        
        }
        
        public function getProductsByArtist($aid, $active_only=1, $page=0, $count=0, $sort='order by create_time DESC')   {
            $sql='select product.*, artist.name from `product` left join `artist` on product.artist_id=artist.artist_id where product.artist_id = '.$aid.($active_only ? ' && product.is_active = 1' : '').' '.$sort.($page*$count ? ' limit '.($page-1)*$count.','.$count : '');
            return $this->db->get_rows($sql);        
        }

        public function getProductByID($pid)    {
            $sql='select product.*, artist.name from `product` left join `artist` on product.artist_id=artist.artist_id where product_id = '.$pid;
            return $this->db->get_one($sql);
        }

        public function addProduct($p)    {            //无图片
            $sql=sprintf("insert into `product` (category_id`, `subject`, `type`, `date`, `artist_id`, `code`, `area`, `condition`, `size`, `price`, `is_active`, `is_sold`, `create_time`) values (%s, '%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', %s, %s, now())", $p['category_id'], mysql_real_escape_string($p['subject']), mysql_real_escape_string($p['type']), mysql_real_escape_string($p['date']), $p['artist_id'], mysql_real_escape_string($p['code']), mysql_real_escape_string($p['area']), mysql_real_escape_string($p['condition']), mysql_real_escape_string($p['size']), mysql_real_escape_string($p['price']), $p['is_active'], $p['is_sold']);
            $this->db->update($sql);
            return $this->db->insert_id();
        }

        public function editProduct($p)    {
            $sql=sprintf("update `product` set `category_id`='%s', `subject`='%s', `type`='%s', `date`='%s', `artist_id`='%s', `code`='%s', `area`='%s', `condition`='%s', `size`='%s', `price`='%s', `is_active`=%s, `is_sold`=%s where `product_id`=%s", $p['category_id'], mysql_real_escape_string($p['subject']), mysql_real_escape_string($p['type']), mysql_real_escape_string($p['date']), $p['artist_id'], mysql_real_escape_string($p['code']), mysql_real_escape_string($p['area']), mysql_real_escape_string($p['condition']), mysql_real_escape_string($p['size']), $p['price'], $p['is_active'], $p['is_sold'], $p['product_id']);
            return $this->db->update($sql); 
        }
        
/**
* 创建商品，并上传图像、调整大小，生成缩略图
* @param    array    $p     商品属性数组，包含category_id
* @param    integer    $imgFile     上传图片，$_FILES文件
*/
        public function createProduct($p,$imgFile)    {            
            $sql='insert into `product` (`category_id`, `create_time`) values ('.$p['category_id'].', now())';
            $this->db->update($sql);
            $pid=$this->db->insert_id();
            if($pid!=0){
                $tmp_url=$imgFile['tmp_name'];//$this->uploadImg($pid,$imgFile);直接由上传临时文件创建图片
                try{
                    $url=$this->createGallery($pid, $tmp_url);
                    $sql='update product set img_url=\''.$url['img_url'].'\', thumb_url=\''.$url['thumb_url'].'\' where product_id='.$pid;
                    $this->db->update($sql);
                }
                catch(Exception $e){
                    $sql='delete from `product` where `product_id`='.$pid;
                    $this->db->update($sql);
                    throw $e;
                }
            }
            return $pid;
        }

        public function deleteProduct($pid)    {       
            $sql='select img_url, thumb_url from `product` where `product_id` = '.$pid;
            $rs=$this->db->get_one($sql);
            $sql='delete from `product` where `product_id`='.$pid;
            $this->db->update($sql);
            if($this->db->affected_rows()>0) {
                @unlink('.'.$rs['img_url']);
                @unlink('.'.$rs['thumb_url']);   
                return true;        
            }
            else return false;
        }
        
                
        public function editGallery($pid, $imgFile){
            $tmp_url=$imgFile['tmp_name'];//$this->uploadImg($pid,$imgFile);
            $sql='select img_url, thumb_url from product where product_id='.$pid;
            $old_url=$this->db->get_one($sql);
            $tmp_img=$old_url['img_url'].'.tmp';
            $tmp_thumb=$old_url['thumb_url'].'.tmp';
            rename('.'.$old_url['img_url'], '.'.$tmp_img);
            rename('.'.$old_url['thumb_url'], '.'.$tmp_thumb);
            try{
                $url=$this->createGallery($pid, $tmp_url);
                $sql='update product set img_url=\''.$url['img_url'].'\', thumb_url=\''.$url['thumb_url'].'\' where product_id='.$pid;
                $this->db->update($sql);
                @unlink('.'.$tmp_img);
                @unlink('.'.$tmp_thumb);
            }
            catch(Exception $e){
                rename('.'.$tmp_img, '.'.$old_url['img_url']);
                rename('.'.$tmp_thumb, '.'.$old_url['thumb_url']); 
                throw $e;               
            }
        }
        
/*        private function uploadImg($pid,$imgFile){    
            $tmp_url='.'.self::IMG_LOCATION.$pid;
            if(!file_exists(self::IMG_LOCATION)){
                @mkdir(self::IMG_LOCATION);
            }
            if(!move_uploaded_file($imgFile['tmp_name'],'.'.$tmp_url)) $tmp_url='';
            return $tmp_url;
        }*/
        
        private function createGallery($pid, $tmp_url){
            $t=new ThumbHandler();
            $siteInfo=new SiteInfo();
            $w=$siteInfo->getWartermark();
            $t->setMaskWord($w['watermark_text']);
            $t->setMaskFont(self::WATERMARK_FONT);
            $t->setMaskTxtPct($w['watermark_transparency']);
            //image
            $t->setSrcImg($tmp_url);
            $img_url=self::IMG_LOCATION.$pid.'.'.$t->img_type;
            $t->setDstImg('.'.$img_url);
            $t->setMaskFontSize(intval($w['watermark_fontsize_img']));
            $t->setMaskOffsetX(self::IMG_WATERMARK_OFFSET_X);
            $t->setMaskOffsetY(self::IMG_WATERMARK_OFFSET_Y);
            $t->createImg(self::IMG_MAX_W,self::IMG_MAX_H);
            //thumb
            $t->setSrcImg($tmp_url);
            $thumb_url=self::IMG_LOCATION.$pid.self::IMG_THUMB_SUFFIX.'.'.$t->img_type;
            $t->setDstImg('.'.$thumb_url);
            $t->setMaskFontSize(intval($w['watermark_fontsize_thumb']));
            $t->setMaskOffsetX(self::THUMB_WATERMARK_OFFSET_X);
            $t->setMaskOffsetY(self::THUMB_WATERMARK_OFFSET_Y);
            try{$t->createImg(self::THUMB_MAX_W,self::THUMB_MAX_H);} catch(Exception $e){@unlink('.'.$img_url); throw $e;}
            @unlink($tmp_url);
            return array('img_url'=>$img_url, 'thumb_url'=>$thumb_url);
        }
    }
?>